package com.example.invoke.service;

import com.example.invoke.entity.User;
import com.example.invoke.entity.UserRepo;
import com.example.invoke.util.RespObj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Component("indexService")
public class IndexService extends CommonService implements BaseService {

    @Autowired
    private IndexService indexService;
    @Autowired
    private BService bService;
    @Autowired
    private UserRepo userRepo;

    @Autowired
    ApplicationContext context;

    @Override
    public String handle (Map source) {
        return doHandle(this.indexService, source);
    }

    @PostConstruct
    public void initData() {
        Optional<User> u1 = userRepo.findById(1L);
        if (u1.isPresent()) {
            User user1 = u1.get();
            user1.setName("1111");
            userRepo.save(user1);
        } else {
            userRepo.save(new User(1L, "1111"));
        }

        Optional<User> u2 = userRepo.findById(2L);
        if (u2.isPresent()) {
            User user2 = u2.get();
            user2.setName("2222");
            userRepo.save(user2);
        } else {
            userRepo.save(new User(2L, "2222"));
        }
        System.out.println(userRepo.findAll());
    }

    @Transactional
    public String getA(String data, RespObj respObj){

        User one = userRepo.getOne(1L);
        one.setName("1111update");
        userRepo.save(one);
        userRepo.updateUser("我是测试", one.getId());

        System.out.println(1 / 0);

        User two = userRepo.getOne(2L);
        two.setName("2222update");
        userRepo.save(two);

        return "getA";
    }

    @Transactional
    public String getB(String data, RespObj respObj){
        bService.printaa();
        return "getB";
    }

    public User addUser(String name) {
        Map map = new HashMap();
        BaseService bean = context.getBean("indexService", BaseService.class);
        map.put("action", "getA");
        map.put("data", "getA");
        System.out.println(bean.handle(map));

        User user = new User();
        user.setName(name);
        return userRepo.save(user);
    }
}
